package com.woniu108.product.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu108.carService.commos.dto.StoreAdminDto;
import com.woniu108.carService.commos.dto.StoreProductDto;
import com.woniu108.carService.commos.exception.admin.AdminException;
import com.woniu108.carService.commos.exception.admin.AdminExceptionCode;
import com.woniu108.carService.commos.exception.produnt.ProductException;
import com.woniu108.carService.commos.exception.produnt.ProductExceptionCode;
import com.woniu108.carService.commos.exception.upload.UpLoadException;
import com.woniu108.carService.commos.exception.upload.UpLoadExceptionCode;
import com.woniu108.carService.commos.util.FileUtil;
import com.woniu108.carService.commos.util.OSSUtil;
import com.woniu108.carService.commos.util.StaticData;
import com.woniu108.product.client.PersonClient;
import com.woniu108.product.mapper.ProductBrandMapper;
import com.woniu108.product.mapper.ProductTypeMapper;
import com.woniu108.product.mapper.StoreProductMapper;
import com.woniu108.product.model.ProductBrand;
import com.woniu108.product.model.ProductType;
import com.woniu108.product.model.StoreProduct;
import com.woniu108.product.param.DeleteStoreProductParam;
import com.woniu108.product.param.InsertStoreProductParam;
import com.woniu108.product.param.OutStorageParam;
import com.woniu108.product.param.PutStorageParam;
import com.woniu108.product.service.StoreProductService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 门店库存表 服务实现类
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@Service
public class StoreProductServiceImpl extends ServiceImpl<StoreProductMapper, StoreProduct> implements StoreProductService {
    @Resource
    private StoreProductMapper storeProductMapper;
    @Resource
    private ProductBrandMapper productBrandMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;
    @Resource
    private PersonClient personClient;
    @Resource
    private OSSUtil ossUtil;

    /**
     * @param spPicture 图片文件
     * @return string 图片地址
     * @throws Exception 自定义异常
     */
    private String handleImageUpload(MultipartFile spPicture) throws Exception {
        // 判断文件类型
        if(spPicture!=null) {
            if (!FileUtil.isImageFile(spPicture.getInputStream())) {
                throw new UpLoadException(UpLoadExceptionCode.FILE_UPLOAD_ERROR);
            }

            String oldName = spPicture.getOriginalFilename();
            if (oldName == null) {
                throw new UpLoadException(UpLoadExceptionCode.FILE_UPLOAD_NULL);
            }

            int lastIndex = oldName.lastIndexOf(".");
            if (lastIndex == -1) {
                throw new UpLoadException(UpLoadExceptionCode.FILE_UPLOAD_LACK_SUFFIX);
            }
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString();

            return ossUtil.uploadFile(spPicture.getInputStream(), fileName + suffix, "class108");
        }else{
            return null;
        }
        }

    /**
     * 判断店家
     */
    private Integer isStore(String storeAdminId) {
        // 检查 adminId 是否为 null
        if (storeAdminId == null) {
            throw new AdminException(AdminExceptionCode.STORE_ADMIN_ID_NULL);
        }
        // 判断店家权限
        StoreAdminDto dto = personClient.getStoreAdminInfoById(storeAdminId).getData();
        if (dto == null) {
            throw new AdminException(AdminExceptionCode.STORE_ADMIN_NOT_HAVE);
        }
        if (!Objects.equals(dto.getStoreAdminState(), StaticData.ADMIN_STATE_NORMAL)) {
            throw new AdminException(AdminExceptionCode.STORE_ADMIN_STATE_ERROR);
        }
        return dto.getStoreId();
    }

    @Override
    public List<StoreProductDto> findMyStoreProduct(String storeAdminId) {
        //得到门店id
        Integer storeId = isStore(storeAdminId);
        //查门店全部商品
        QueryWrapper<StoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("store_id", storeId).ne("sp_info_state", StaticData.STORE_PRODUCT_INFO_STATE_DELETE);
        List<StoreProduct> list = storeProductMapper.selectList(wrapper);
        //设dto集合
        ArrayList<StoreProductDto> dtos = new ArrayList<>();
        for (StoreProduct product : list) {
            //复制相同信息
            StoreProductDto dto = BeanUtil.toBean(product, StoreProductDto.class);
            //查种类名
            ProductType type = productTypeMapper.selectById(product.getPTId());
            dto.setPTName(type.getPTName());
            //查品牌名
            ProductBrand brand = productBrandMapper.selectById(product.getPBId());
            dto.setPBName(brand.getPBName());
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public Boolean insertStoreProduct(InsertStoreProductParam param) throws Exception {
        //得到门店id
        Integer storeId = isStore(param.getStoreAdminId());
        //图片转化
        String spPicture = handleImageUpload(param.getSpPicture());
        //通过名字和门店id查商品是否存在
        QueryWrapper<StoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("sp_info_name",param.getSpInfoName())
                .eq("store_id",storeId);
        StoreProduct product = storeProductMapper.selectOne(wrapper);
        if (product!=null){
            if (Objects.equals(product.getSpInfoState(), StaticData.STORE_PRODUCT_INFO_STATE_DELETE)){
                product.setSpPicture(spPicture);
                product.setSpInfoState(StaticData.STORE_PRODUCT_INFO_STATE_NORMAL);
                product.setCreateTime(LocalDateTime.now());
                int update = storeProductMapper.updateById(product);
                return update>0;
            }
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_HAVE);
        }
        //复制信息
        StoreProduct storeProduct = BeanUtil.toBean(param, StoreProduct.class);
        //补充信息
        storeProduct.setSpPicture(spPicture);
        storeProduct.setStoreId(storeId);
        storeProduct.setSpInfoState(StaticData.STORE_PRODUCT_INFO_STATE_NORMAL);
        storeProduct.setCreateTime(LocalDateTime.now());
        int insert = storeProductMapper.insert(storeProduct);
        return insert>0;
    }

    @Override
    public Boolean putStorage(PutStorageParam param) {
        Integer storeId=null;
        if (param.getStoreAdminId()!=null){
            //得到门店id
           storeId = isStore(param.getStoreAdminId());
        }
        //查询商品
        StoreProduct product = storeProductMapper.selectById(param.getSpInfoId());
        //判断商品
        if (product==null){
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        if (!Objects.equals(product.getStoreId(), storeId)){
            throw new ProductException(ProductExceptionCode.STORE_PRODUCT_NOT_YOUR_STORE);
        }
        //入库，增加数量
        product.setRestNum(product.getRestNum().add(BigDecimal.valueOf(param.getNum())));
        int update = storeProductMapper.updateById(product);
        return update>0;
    }

    @Override
    public Boolean outStorage(OutStorageParam param) {
        Integer storeId=null;
        if (param.getStoreAdminId()!=null){
            //得到门店id
         storeId = isStore(param.getStoreAdminId());
        }
        //查询商品
        StoreProduct product = storeProductMapper.selectById(param.getSpInfoId());
        //判断商品
        if (product==null){
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        if (!Objects.equals(product.getStoreId(), storeId)){
            throw new ProductException(ProductExceptionCode.STORE_PRODUCT_NOT_YOUR_STORE);
        }
        //出库，减少数量
        product.setRestNum(product.getRestNum().subtract(BigDecimal.valueOf(param.getNum())));
        int update = storeProductMapper.updateById(product);
        return update>0;
    }

    @Override
    public Boolean deleteStoreProduct(DeleteStoreProductParam param) {
        //得到门店id
        Integer storeId = isStore(param.getStoreAdminId());
        //查询商品
        StoreProduct product = storeProductMapper.selectById(param.getSpInfoId());
        //判断商品
        if (product==null){
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        if (!Objects.equals(product.getStoreId(), storeId)){
            throw new ProductException(ProductExceptionCode.STORE_PRODUCT_NOT_YOUR_STORE);
        }
        product.setSpInfoState(StaticData.STORE_PRODUCT_INFO_STATE_DELETE);
        int update = storeProductMapper.updateById(product);
        return update>0;
    }

    @Override
    public StoreProductDto findOneStoreProductById(Integer spInfoId) {
        StoreProduct product = storeProductMapper.selectById(spInfoId);
        if (product==null|| Objects.equals(product.getSpInfoState(), StaticData.STORE_PRODUCT_INFO_STATE_DELETE)){
            throw new ProductException(500,"该商品不存在");
        }
        //复制相同信息
        StoreProductDto dto = BeanUtil.toBean(product, StoreProductDto.class);
        //查种类名
        ProductType type = productTypeMapper.selectById(product.getPTId());
        dto.setPTName(type.getPTName());
        //查品牌名
        ProductBrand brand = productBrandMapper.selectById(product.getPBId());
        dto.setPBName(brand.getPBName());
        return dto;
    }
}
